import java.io.*;

class LineMarket
{
	public static void main(String args[])
	{
		ShareDoc doc = new ShareDoc("log.txt");
		LineProducer producer1 = new LineProducer(doc,1);
		LineProducer producer2 = new LineProducer(doc,2);
		LineConsumer consumer = new LineConsumer(doc);
		producer1.start();
		producer2.start();
		consumer.start();
	}
}

class ShareDoc
{
	private File file ;
	private BufferedReader input;
	private PrintStream output;
	private int length;
	public ShareDoc(String str)
	{
		length = 0;
		try
		{
			file=new File(System.getProperty("user.dir"),str);
			file.createNewFile();
			input=new BufferedReader(new FileReader(file));
			output=new PrintStream(file);
		}catch(Exception e){
			System.out.println("IOError!");
			System.exit(-1);
		}
	}
	
	public synchronized String readLine()	//锁的运用是个关键
	{
		String str = new String();
		try
		{
			while( length == 0)
				this.wait();
				
			str = input.readLine();
			length --;
				return str;
		}catch(Exception e)
		{
			System.out.println("ReadError!");
			System.exit(-1);
		}
		return str;
	}
	public synchronized void writeLine(String string)
	{
		if(length != 0)
			this.notify();
		output.println(string);
		length ++;
	}
}

class LineProducer extends Thread
{
	private ShareDoc io;
	private int num;
	public LineProducer(ShareDoc doc,int i)
	{
		io = doc;
		num = i;
	}
	
	public void run()
	{
		for (int i = 1; i <= 30; i++)
		{
			io.writeLine("line " + i + " from LineProducer " + num);
			try
			{
				sleep(100);
			}catch (InterruptedException e)
			{
				System.out.println("Error!");
				System.exit(-1);
			}
		}
		io.writeLine("File End");	//有没有更好的方法？？不必采用协议？？
	}
}

class LineConsumer extends Thread
{
	private ShareDoc io;
	public LineConsumer(ShareDoc doc)
	{
		io = doc;
	}
	public void run()
	{
		String str = new String();
		while(true)
		{
			if(!(str = io.readLine()).equals("File End"))
				System.out.println("LineConsumer: "+str);
			else
				return;
		}
			
	}
}
